﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace SX.Core.Helper
{
    /// <summary>
    /// 文件操作相关
    /// </summary>
    public class FileHepler
    {
        /// <summary>
        /// 压缩文件流或者远端流
        /// </summary>
        public static void CompressStream(Stream sourceStream)
        {
            //FileStream sourceStream = new FileStream(@"C:\Users\Administrator\Desktop\aaa.txt", FileMode.Open);//可以是远端文件流
            MemoryStream ms = new MemoryStream();
            var zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms);
            if (sourceStream.Length > 0)
            {
                byte[] bytes = new byte[sourceStream.Length];
                sourceStream.Read(bytes, 0, sourceStream.Length.To_Int());
                sourceStream.Seek(0, SeekOrigin.Begin);

                //往压缩包添加第一个文件
                ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("TestFile\\1.txt");
                zipEntry.DateTime = DateTime.Now;
                zipEntry.IsUnicodeText = true;
                zipStream.PutNextEntry(zipEntry);
                zipStream.Write(bytes, 0, bytes.Length);//这里文件过大需要分段读取
                zipStream.CloseEntry();

                //再添加一个文件
                ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry2 = new ICSharpCode.SharpZipLib.Zip.ZipEntry("TestFile\\2.txt");
                zipEntry.DateTime = DateTime.Now;
                zipEntry.IsUnicodeText = true;
                zipStream.PutNextEntry(zipEntry2);
                zipStream.Write(bytes, 0, bytes.Length); //这里文件过大需要分段读取
                zipStream.CloseEntry();


                //使用流操作时一定要设置IsStreamOwner为false。否则很容易发生在文件流关闭后的异常。
                zipStream.IsStreamOwner = false;
                zipStream.Finish();
                zipStream.Close();
            }

            FileStream dest = new FileStream(@"D:\1.zip", FileMode.OpenOrCreate, FileAccess.Write);
            ms.Position = 0;
            ms.CopyTo(dest);
            ms.Close();
            zipStream.Close();
        }
    }
}
